/****同步课程***/
//记录本地已有的课程id
var currCourseids;
//记录所有课程数据，以便存储到本地
var courseList;
var courseCount = 1;
//公共类
var localStorageManagers = require("script/localStorageManagers.js");
var downloadUtils = require('scripts/Core/DownLoadUtil.js');
var mobileFrame = require('scripts/Core/MobileFrame.js');
(function($) {
	mui.init({
		swipeBack: true //启用右滑关闭功能
		//pullRefresh: {
		//	container: '#pullrefresh',
		//	down: {
		//		callback: pulldownRefresh
		//	}
		//}
	});

	$.plusReady(function() {
        //滚动条
	    mui('.mui-scroll-wrapper').scroll({
					indicators: false //是否显示滚动条
				});
		currCourseids = ',';
		courseList = new Array();
		loadCourse();
		mui('#coursesdiv').on('tap', '.mui-course', showResView);

	});

})(mui);
//加载课程
function loadCourse(){
	document.getElementById('coursesdiv').innerHTML=' ';
	if (hasNet()) {
		loadCourseAjax(); //ajax加载课程
	}else{
		var tipstr='<div class="nettip" id="nettip" style="display:block;margin-bottom:20px;"><span class="nt2">当前网络不可用,请检查你的网络设置</span></div>';
		document.getElementById('coursesdiv').innerHTML=tipstr;
		loadCourseLocal(); //加载本地课程
	}
}
//是否有网
function hasNet() {
	var isNet = mobileFrame.IsNetWorkCanUse();
	return isNet;
}
//本地加载
function loadCourseLocal() {
	courseList = localStorageManagers.getSynccourseSession();
	if (courseList != null) {
		var courseulEle = document.getElementById("coursesdiv");
		mui.each(courseList, function(index, course) {
			currCourseids += course.courseId + ",";
			buildCourseDiv(course);
			courseCount++;
		});
	}
}
//远程加载课程列表数据
function loadCourseAjax() {
	if (courseList == null) courseList = new Array();
	if(currCourseids.length>0)currCourseids=currCourseids.substring(0,currCourseids.length-1);
	//var userid = localStorage.getItem("userid");
	var userid = localStorageManagers.getUseridSession();
	console.log(serverAjax + 'mobile/course/getCourseList.do');
	var w=plus.nativeUI.showWaiting();
	mui.ajax(serverAjax + 'mobile/course/getCourseList.do', {
		data: {
			userid: userid,
			currCourseids: currCourseids
		},
		dataType: 'json', //服务器返回json格式数据
		type: 'post', //HTTP请求类型
		timeout: 10000, //超时时间设置为10秒；
		success: function(data) {
			if (data.length == 0) {
				w.close();
				ifHasnewCourse = false;
				return;
			}
			for (var i = 0; i < data.length; i++) {
				var course = data[i];
				courseList.push(course);
				buildCourseDiv(course);
				courseCount++;
			}
			localStorageManagers.setSynccourseSession(courseList);
			w.close();
		},
		error: function(xhr, type, errorThrown) {
			w.close();
			ajaxErrorTip();
			//异常处理；
			console.log(xhr);
		}
	});
}
//打开课程资源页面
function showResView() {
	var courseid = this.getAttribute('courseid');
	mui.openWindow({
		url: 'resView.html',
		id: 'synccourse/resView',
		styles:getStyles(),
		extras: {
			'courseid': courseid
		}
	});
}

function getBackColor() {
	var bColor = 'b1';
	var yu = courseCount % 4;
	switch (yu) {
		case 1:
			bColor = 'b1';
			break;
		case 2:
			bColor = 'b2';
			break;
		case 3:
			bColor = 'b3';
			break;
		case 0:
			bColor = 'b4';
			break;
	}
	return bColor;
}
//构建课程div
function buildCourseDiv(course) {
	
	var courseDivEle = document.getElementById('courseid_' + course.courseId);
	if (courseDivEle != null) courseDivEle.parentNode.removeChild(courseDivEle);
	var bColor = getBackColor();
	var divstr = '<div class="mui-course" id="courseid_' + course.courseId + '" courseid="' + course.courseId + '">' + '<div class="course-top ' + bColor + '">' + '<div class="c1">' + '<span class="cmsg"><img src="../images/tip.png" />&nbsp;教师上传了计机械设计机械设计机</span> ' + '<span class="cname">' + course.title + '</span>  ' + '<span class="ctype">'+course.catName+'</span>' + ' </div>' + '<div class="c2">' + '	<span class="cuser"><img src="../images/tou.png" />&nbsp;' + course.creator + '</span>' + '</div>' + '</div>' + '<div class="course-foot">' + '<span class="title">学习课程</span><span class="navigate-right"></span>' + '</div>' + '</div>';
	document.getElementById('coursesdiv').innerHTML = document.getElementById('coursesdiv').innerHTML + divstr;
}
//下载资源
function downloadResource(src) {
	// plus.downloader.enumerate(function(tasks){
	//  	alert("当前下载任务数量:"+tasks.length);
	//  });
	//调用父页面方法
	downloadUtils.downloadFileWidthLocalCache(src, {
		beforeDownload: function() {
			//记录该下载资源信息：资源本身信息，课程、课题信息
		},
		successDownload: function(relativePath) {
			console.log('下载成功:' + relativePath);
			var resWebView = plus.webview.getWebviewById("synccourse/resView");
	        resWebView.evalJS("downFinish('" + src + "')");
			//alert('下载成功:' + relativePath);
			mui.plusReady(function() {
				var sd_path = plus.io.convertLocalFileSystemURL(relativePath);
				console.log('存储路径：' + sd_path);
			});
		},
		errorDownload: function(msg) {}
	});
	//var curTasks=DownloadUtil.getCurrentDownloadTasks();
	//var conCurTasks=DownloadUtil.getConcurrentDownloadTask();
	// mui.toast("当前下载任务数量:"+conCurTasks.CurrentTaskCount);
};

/**
 * 下拉刷新具体业务实现
 */
function pulldownRefresh() {
	setTimeout(function() {
		//刷新
		currCourseids = ',';
		courseList = new Array();
		courseCount = 1;
		if (hasNet()) 
		loadCourseAjax(); 
		//loadCourse();
		mui('#pullrefresh').pullRefresh().endPulldownToRefresh(); //refresh completed
	}, 1000);
}
var count = 0;
/**
 * 上拉加载具体业务实现
 */
var ifHasnewCourse = true;

function pullupRefresh() {
 // alert(1);
	setTimeout(function() {
		ifHasnewCourse = true;
		loadCourseAjax();
		mui('#pullrefresh').pullRefresh().endPullupToRefresh(ifHasnewCourse); //参数为true代表没有更多数据了。
		ifHasnewCourse = true;
	}, 1500);
}